package com.example.baseutils.ui

import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.CountDownTimer
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import com.example.baseutils.NavigationBarUtil.hideNavigationBar
import com.example.baseutils.R


class ProgressDialog(context: Context) : AlertDialog(context) {
    private val TAG = "ProgressDialog"
    var isShow = false
    var canOut: Boolean = true
    var countDownTimer: CountDownTimer? = null

    private var tv_message:TextView?=null
    public interface ProcessCallBack {
        fun timeEnd()
    }

    fun init(out: Boolean = true): ProgressDialog {
        this.canOut = out
        Builder(context).create()
        setCanceledOnTouchOutside(canOut)
//        setCancelable(false)
//        val inflater = LayoutInflater.from(context)
//        val view = inflater.inflate(R.layout.dialog_progress, null)
//        setView(view)
        return this
    }

    fun showProgress(textInfo: String, out: Boolean = true) {
        this.canOut = out
        dismissDialog()
        setCanceledOnTouchOutside(canOut)
        isShow = true
        show()
        window?.let {
            hideNavigationBar(it)
            it.setContentView(R.layout.dialog_progress)
            it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            it.findViewById<TextView>(R.id.tv_message).text=textInfo
        }
    }

    override fun onBackPressed() {
        if (canOut)
            super.onBackPressed()

    }

    fun updateListText(totalTime: Long, processCallBack: ProcessCallBack? = null) {
        if (!isShow)
            return
        var index = (totalTime / 1000L).toInt()
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(totalTime, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                if (!isShow) {
                    dismissDialog()
                    cancel()
                    return
                }
                if (index-- > 1) {
                    tv_message?.text = "即将开始 $index"
                }
            }

            override fun onFinish() {
                processCallBack?.timeEnd()
                dismissDialog()
            }
        }.start()

    }

    fun dismissDialog() {
        if (isShow) {
            canOut=false
            countDownTimer?.cancel()
            countDownTimer = null
            isShow = false
            dismiss()
        }
    }

}